package com.cracker.sso.service;

import com.cracker.sso.dao.UserDao;
import com.cracker.sso.dto.request.LoginDto;
import com.cracker.sso.dto.request.RegisterDto;
import com.cracker.sso.dto.response.UserDto;
import com.cracker.sso.event.UserLoginEvent;
import com.cracker.sso.event.UserRegisterEvent;
import com.cracker.sso.mapper.UserMapper;
import com.cracker.sso.model.UserModel;
import com.cracker.sso.tool.AuthTool;
import com.tool.base.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private ApplicationContext context;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AuthTool authTool;

    public UserDto register(RegisterDto registerDto) {
        UserModel userModel = userDao.getByAccount(registerDto.getUserName());
        if (null != userModel) {
            throw new ApiException("用户已注册", 500);
        }
        userModel = new UserModel();
        userModel.setAccount(registerDto.getUserName());
        userModel.setPassword(authTool.generalPassword(registerDto.getPassword()));
        userModel = userDao.save(userModel);
        context.publishEvent(new UserRegisterEvent(this, userModel));
        return userMapper.modelToDto(userModel);
    }

    public UserDto login(LoginDto loginDto) {
        UserModel userModel = userDao.getByAccount(loginDto.getUserName());
        if (null == userModel || !authTool.verifyPassword(loginDto.getPassword(), userModel.getPassword())) {
            throw new ApiException("账号或密码错误", 500);
        }
        context.publishEvent(new UserLoginEvent(this, userModel));
        return userMapper.modelToDto(userModel);
    }

}
